<script lang="ts" setup>
import { MessagePlugin } from 'tdesign-vue-next'
import { LockOnIcon, SecuredIcon, UserIcon } from 'tdesign-icons-vue-next'
import { computed, reactive, ref } from 'vue'
import { post } from '@/utils/api'
import router from '@/router'

const formData = reactive({
  email: '',
  password: '',
  captcha: ''
})

const loading = ref(false)

const rules = {
  email: [{ required: true, trigger: 'blur' }],
  password: [
    { required: true, trigger: 'blur' },
    { min: 10, message: '密码至少为10位' }
  ],
  captcha: [{ required: true, trigger: 'blur' }]
}

const emailSuffix = ['@qq.com', '@163.com', '@gmail.com', '@outlook.com']
const emailOptions = computed(() => {
  const emailPrefix = formData.email.split('@')[0]
  if (!emailPrefix) return []
  return emailSuffix.map((suffix) => emailPrefix + suffix)
})

const formRef = ref<any>(null)
const register = async () => {
  const result = await formRef.value.validate()
  if (result === true) {
    loading.value = true
    const response = await post('/api/user/register', formData)
    MessagePlugin(response.status, response.message)
    if (response.status === 'success') {
      await router.push('/login')
    }
    loading.value = false
  }
}

const sendCaptchaStatus = ref(false)
const sendCaptchaText = computed(() => {
  if (sendCaptchaStatus.value) {
    return `已发送 ${countDownSeconds.value}`
  } else {
    return '发送验证码'
  }
})
const sendCaptchaDisabled = ref(false)
const sendCaptcha = () => {
  sendCaptchaStatus.value = true
  sendCaptchaDisabled.value = true
  countDown()
  executeSend()
}
const countDownSeconds = ref(60)
const countDown = () => {
  const countInterval = setInterval(() => {
    countDownSeconds.value--
    if (countDownSeconds.value < 1) {
      clearInterval(countInterval)
      sendCaptchaDisabled.value = false
      sendCaptchaStatus.value = false
      countDownSeconds.value = 60
    }
  }, 1000)
}
const executeSend = async () => {
  await post('/api/email/send', { to: formData.email })
}
</script>

<template>
  <t-row class="container">
    <t-col :lg="6" :md="6" :sm="12" :xl="6" :xs="12">
      <t-card header-bordered>
        <template #header>
          <img
            alt=""
            src="../../../assets/images/author/logo_light.png"
            width="110"
            style="margin: -12px auto"
          />
        </template>

        <t-form ref="formRef" :data="formData" :rules="rules" class="form" label-align="top">
          <t-form-item label="邮箱" name="email">
            <t-auto-complete
              v-model="formData.email"
              :options="emailOptions"
              placeholder="请输入邮箱"
            >
              <template #prefix-icon>
                <UserIcon />
              </template>
            </t-auto-complete>
          </t-form-item>

          <t-form-item label="密码" name="password">
            <t-input v-model="formData.password" clearable placeholder="请输入密码" type="password">
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
          </t-form-item>

          <t-form-item label="验证码" name="captcha">
            <t-row class="captcha_container">
              <t-input v-model="formData.captcha" class="captcha_input" placeholder="请输入验证码">
                <template #prefix-icon>
                  <SecuredIcon />
                </template>
              </t-input>
              <t-button
                theme="default"
                @click="sendCaptcha"
                :disabled="sendCaptchaDisabled"
                class="send_captcha"
              >
                {{ sendCaptchaText }}
              </t-button>
            </t-row>
          </t-form-item>

          <t-form-item>
            <t-button :loading="loading" block theme="primary" @click="register">注册</t-button>
          </t-form-item>
        </t-form>

        <template #footer>
          <div class="footer">
            <t-link hover="color" content="已有账号？立即登录" href="/login" />
          </div>
        </template>
      </t-card>
    </t-col>
  </t-row>
</template>

<style lang="less" scoped>
.container {
  width: 100vw;
  height: calc(100vh - 98px);
  background-color: #f5f5f5;
  background-image: url('@/assets/images/author/login-bg.png');
  background-size: cover;

  .t-col {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .t-card {
      width: 360px;

      .logo_container {
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
      }

      .captcha_container {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .captcha_input {
          width: 180px;
        }
      }
    }
    .footer {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-top: -15px;
    }
  }
}
img {
  user-select: none;
}
</style>
